package cn.fraudmetrix.octopus.modules.jacoco.service;

import cn.fraudmetrix.octopus.modules.jacoco.constant.JacocoConstant;
import org.apache.commons.io.FileUtils;
import org.jacoco.core.data.ExecutionDataWriter;
import org.jacoco.core.runtime.RemoteControlReader;
import org.jacoco.core.runtime.RemoteControlWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author libao.zheng
 * @email libao.zheng@tongdun.cn
 * @date 2018/12/5 11:26
 */
public class ExecutionDataClient {
    public static void dump(final String appName, final String ip, final int port, boolean clearHistory) throws Exception {
        String execFileDirectory = JacocoConstant.LOCAL_RESOURCE + appName;
        File file = new File(execFileDirectory);
        if (!file.exists()) {
            FileUtils.forceMkdir(file);
        }
        FileOutputStream localFile = new FileOutputStream(execFileDirectory + JacocoConstant.JACOCO_FILE_NAME);
        ExecutionDataWriter localWriter = new ExecutionDataWriter(localFile);
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), 3000);
        RemoteControlWriter writer = new RemoteControlWriter(socket.getOutputStream());
        RemoteControlReader reader = new RemoteControlReader(socket.getInputStream());
        reader.setSessionInfoVisitor(localWriter);
        reader.setExecutionDataVisitor(localWriter);
        writer.visitDumpCommand(true, clearHistory);
        if (!reader.read()) {
            throw new IOException("Socket closed unexpectedly.");
        }
        socket.close();
        localFile.close();
    }

}